package training.osms.persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;


public abstract class AbstractManagerTemplate {

		public void execute() {
			EntityManager manager = null;
			EntityTransaction transaction = null;

			try {
				manager = EntityManagerFactorySingleton.FACTORY.createEntityManager();
				transaction = manager.getTransaction();
				transaction.begin();
				
				execute(manager);				
				
				manager.flush();
				transaction.commit();

			}catch(RuntimeException e) {
				if (transaction != null){
					try{
					transaction.getRollbackOnly();
					}catch (RuntimeException ex) {
					
					}
					throw e;
				}
			}finally{
				try{
					if (manager != null){
						manager.close();
					}				
				}catch(RuntimeException e){
					e.printStackTrace();
				}
			}
		}

		protected abstract void execute(EntityManager manager);
}
